<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\model\api;

use laytp\BaseModel;
use think\model\concern\SoftDelete;

class GenshinTeam extends BaseModel
{
    use SoftDelete;

    protected $deleteTime = 'delete_time';


    /**
     * 标签列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTagList(){
        $list = $this
            ->cache(true)
            ->column('tag');
        $list = array_values(array_filter(array_unique($list)));
        return $list;
    }

    /**
     * 组队列表
     * @param int $is_backend
     * @param string $category
     * @param string $tag
     * @param string $role_ids
     * @param string $openid
     * @param array $where
     * @param string $sort
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function teamList($is_backend,$category,$tag,$role_ids,$openid,$where = [],$sort = '1',$page = 1,$limit = 10){
        //排序
        if($sort == 1){
            $sort = 'sort desc,create_time desc';
        }else{
            $sort = 'create_time desc';
        }

        if(!$is_backend){
            $where[] = ['status','=',1];
        }

        if($category){
            $where[] = ['keywords', 'like', '%"'.$category.'"%'];
        }
        if($tag){
            $where[] = ['tag', '=', $tag];
        }
        $list = $this->where(function($query) use ($role_ids){
            if(!empty($role_ids)){
                $role_ids = explode(',',$role_ids);
                $query->where(function($query1) use ($role_ids){
                    foreach($role_ids as $choose_id){
                        $query1->where(array(
                            'top_main_role_id|top_vice_role_id|top_assist1_role_id|top_assist2_role_id' => $choose_id
                        ));
                    }
                });
                $query->whereOr(function($query2) use ($role_ids){
                    foreach($role_ids as $choose_id){
                        $query2->where(array(
                            'bottom_main_role_id|bottom_vice_role_id|bottom_assist1_role_id|bottom_assist2_role_id' => $choose_id
                        ));
                    }
                });
            }
        })->where($where)
            ->order($sort)
            ->paginate($limit)
            ->toArray();
        $teamIds = array_column($list['data'],'id');
        $authorIds = array_column($list['data'],'author_id');
        $genshinCollectModel = new GenshinCollect();
        $collect_ids = $genshinCollectModel->getCollect($openid);
        $like_ids = (new GenshinLike())->getLike($openid);
        //角色位置
        $role_position = (new GenshinTeamRole())->teamRolePosition($teamIds);
        //作者信息
        $author = (new GenshinAuthor())->getAllAuthor($authorIds);


        $return_data = [];
        foreach($list['data'] as $item){
            $style = 0;
            $isCollect = 0;
            $isLike = 0;
            $teamList = [];

            if(!empty($item['bottom_main_role_id'])){
                $style = 1;
                $teamList['step1'][] = self::teamRole($role_position[$item['id']][1][$item['top_main_role_id']],$item['top_main_role_id']);
                $teamList['step1'][] = self::teamRole($role_position[$item['id']][1][$item['top_vice_role_id']],$item['top_vice_role_id']);
                $teamList['step1'][] = self::teamRole($role_position[$item['id']][1][$item['top_assist1_role_id']],$item['top_assist1_role_id']);
                $teamList['step1'][] = self::teamRole($role_position[$item['id']][1][$item['top_assist2_role_id']],$item['top_assist2_role_id']);

                $teamList['step2'][] = self::teamRole($role_position[$item['id']][2][$item['bottom_main_role_id']],$item['bottom_main_role_id']);
                $teamList['step2'][] = self::teamRole($role_position[$item['id']][2][$item['bottom_vice_role_id']],$item['bottom_vice_role_id']);
                $teamList['step2'][] = self::teamRole($role_position[$item['id']][2][$item['bottom_assist1_role_id']],$item['bottom_assist1_role_id']);
                $teamList['step2'][] = self::teamRole($role_position[$item['id']][2][$item['bottom_assist2_role_id']],$item['bottom_assist2_role_id']);
            }else{
                $teamList[] = self::teamRole($role_position[$item['id']][1][$item['top_main_role_id']],$item['top_main_role_id']);
                $teamList[] = self::teamRole($role_position[$item['id']][1][$item['top_vice_role_id']],$item['top_vice_role_id']);
                $teamList[] = self::teamRole($role_position[$item['id']][1][$item['top_assist1_role_id']],$item['top_assist1_role_id']);
                $teamList[] = self::teamRole($role_position[$item['id']][1][$item['top_assist2_role_id']],$item['top_assist2_role_id']);
            }

            if(in_array($item['id'],$collect_ids)){
                $isCollect = 1;
            }
            if(in_array($item['id'],$like_ids)){
                $isLike = 1;
            }

            $return_data[] = array(
                'id'        => $item['id'],
                'author_id' => $item['author_id'],
                'author'    => !empty($author[$item['author_id']]['author_name'])?$author[$item['author_id']]['author_name']:'',
                'avatar'    => !empty($author[$item['author_id']]['author_head'])?$author[$item['author_id']]['author_head']:'',
                'tag'       => $item['tag'],
                'title'     => $item['team_name'],
                'teamlist'  => $teamList,
                'keywords'  => json_decode($item['keywords'],true),
                'style'     => $style,
                'cover'     => $item['cover'],
                'isCollect' => $isCollect,
                'isLike'    => $isLike,
                'likeCount'  => $item['like_num'],
                'is_publish'  => $item['is_publish'],
            );
        }

        return array(
            'data'=>$return_data,
            'total'=> $list['total'],
            'per_page' => $list['per_page'],
            'current_page'=> $list['current_page'],
            'last_page' => $list['last_page']
        );
    }

    /**
     * 队伍详情
     * @param $team_id
     * @param $openid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function teamDetail($team_id,$openid){
        error_reporting(0);
        $team_role_model = new GenshinTeamRole();

        $teamDetail = $this->where('id',$team_id)->cache(true)->find();
        $teamList = [];
        $team_role = $team_role_model->teamRoleInfo($team_id);
        if(!empty($teamDetail['bottom_main_role_id'])){
            $style = 1;
            $teamList['step1'] = array_values($team_role[1]);;
            $teamList['step2'] = array_values($team_role[2]);;

            $reaction['step1'] = json_decode($teamDetail['reaction'],true);
            $reaction['step2'] = json_decode($teamDetail['reaction_bottom'],true);
        }else{
            $style = 0;

            $teamList = array_values($team_role[1]);
            $reaction = json_decode($teamDetail['reaction'],true);
        }

        $genshinCollectModel = new GenshinCollect();
        $collect_ids = $genshinCollectModel->getCollect($openid);
        //作者信息
        $author = (new GenshinAuthor())->getAllAuthor([$teamDetail['author_id']]);
        $return = array(
            'id'          => $teamDetail['id'],
            'author'      => !empty($author[$teamDetail['author_id']]['author_name'])?$author[$teamDetail['author_id']]['author_name']:$teamDetail['author_id'],
            'avatar'      => !empty($author[$teamDetail['author_id']]['author_head'])?$author[$teamDetail['author_id']]['author_head']:'http://agent-1.oss-cn-beijing.aliyuncs.com/reset/uid2/member/20220519/genshin_imgAmber.png',
            'tag'         => $teamDetail['tag'],
            'create_time' => date('Y-m-d',strtotime($teamDetail['create_time'])),
            'title'       => $teamDetail['team_name'],
            'keywords'    => json_decode($teamDetail['keywords'],true),
            'isCollect'   => in_array($team_id,$collect_ids)?1:0,
            'style'       => $style,
            'teamlist'    => $teamList,
            'reaction'    => $reaction,
            'description' => $teamDetail['team_desc']
        );

        return $return;
    }

    /**
     * 角色详情
     * @param $type
     * @param $team_id
     * @param $role_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function teamRole($position,$role_id){
        $role_info = (new GenshinRole())->roleInfo();

        return array(
            'id' => $role_id,
            "name"     => $role_info[$role_id]['role_name'],
            "avatar"   => $role_info[$role_id]['head_img'],
            "element"  => $role_info[$role_id]['element'],
            "nation"   => $role_info[$role_id]['nation'],
            "position" => $position,
            "stars"    => $role_info[$role_id]['star'],
        );
    }
}